var express = require('express');
var router = express.Router();
//引入数据库
var connection = require('../db/sql.js')

//引入查询用户手机号以及密码的sql语句
var user = require('../db/userSql.js')

//引入token以及解析token的包
var jwt = require('jsonwebtoken')

//引入短信验证码的包
var QcloudSms = require("qcloudsms_js");

//引入支付宝配置文件
const alipaySdk = require('../db/alipay.js')
const AlipayFormData = require("alipay-sdk/lib/form").default

//引入axios
const axios = require('axios')

//获取token的过期时间
function getTimeToken(exp) {
    // 因为在Date方法中获取时间的单位为毫秒 而token的单位为秒
    let getTime = parseInt(new Date().getTime() / 1000)
        //过期时间为10分钟 >后面的数字为过期时间 单位是秒
    if (getTime - exp > 600) {
        return true
    }
}



/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

// 首页推荐的数据
router.get('/api/index_list/0/data/1', function(req, res, next) {
    res.send({
        data: {
            //这是顶部切换栏的数据
            topBar: [
                { id: 1, label: '推荐' },
                { id: 2, label: '零食礼包' },
                // { id: 3, label: '下午茶' },
                // { id: 4, label: '低卡零食' },
                // { id: 5, label: '卤味' },
                // { id: 6, label: '进口零食' },
                // { id: 7, label: '糕点' },
                // { id: 8, label: '糕辣条' },
            ],
            //首页的数据
            Homedata: [
                //swiper轮播图的数据
                {
                    id: 0,
                    type: 'swiperList',
                    data: [
                        { id: 0, imgUrl: './images/swiper1.jpeg' },
                        { id: 2, imgUrl: './images/swiper2.jpeg' },
                        { id: 3, imgUrl: './images/swiper3.jpeg' },
                    ]
                },
                //icons图标
                {
                    id: 1,
                    type: 'iconsList',
                    data: [{
                            id: 1,
                            title: '零食礼包',
                            imgUrl: './images/零食礼包.png'
                        },
                        {
                            id: 2,
                            title: '干货',
                            imgUrl: './images/binggan.jpeg'
                        },
                        {
                            id: 3,
                            title: '肉食',
                            imgUrl: './images/roushi.jpeg'
                        },
                        {
                            id: 4,
                            title: '甜品',
                            imgUrl: './images/tianping.jpeg'
                        },
                        {
                            id: 5,
                            title: '辣条',
                            imgUrl: './images/latiao.jpeg'
                        },
                    ]
                },
                //爆款推荐数据
                {
                    id: 2,
                    type: 'recommendList',
                    data: [{
                            id: 7,
                            imgUrl: '/images/xiongmaogaodian.png',
                            content: '好利来熊猫竹竹点心零食糕点点心早餐小吃礼盒',
                            name: '好利来熊猫点心',
                            price: '28.00'
                        },
                        {
                            id: 8,
                            imgUrl: '/images/fengzhua.jpeg',
                            content: '王小卤虎皮凤爪爆款零食小吃 休闲食品鸡爪子卤味熟食解馋小零食',
                            name: '王小陆虎皮凤爪',
                            price: '24.95'
                        },
                        {
                            id: 9,
                            imgUrl: '/images/moyushuang.jpeg',
                            content: '卫龙魔芋爽辣条魔芋素毛肚素肉好吃办公室零食小吃休闲食品大礼包',
                            name: '卫龙魔芋爽',
                            price: '16.90'
                        }
                    ]
                },
                //猜你喜欢数据
                {
                    id: 4,
                    type: 'likeList',
                    data: [{
                            id: 1,
                            imgUrl: '/images/recommend1.jpeg',
                            name: '爆款零食大礼包，买一箱送一箱品牌零食,好吃不贵，送女友必备！',
                            price: '69.80'
                        },
                        {
                            id: 2,
                            imgUrl: '/images/recommend2.jpeg',
                            name: '众望小麻花，好吃不贵，吃麻花就选众望！',
                            price: '19.80'
                        },
                        {
                            id: 3,
                            imgUrl: '/images/recommend3.jpeg',
                            name: '知味艾草青团，网红芝士奶酪青团,天然艾草,百年老字号',
                            price: '18.53'
                        },
                        {
                            id: 4,
                            imgUrl: '/images/recommend4.jpeg',
                            name: '法丽兹网红夹心饼干，招牌夹心曲奇.4种口味',
                            price: '39.80'
                        },
                        {
                            id: 5,
                            imgUrl: '/images/dalibao2.jpeg',
                            name: '零食大礼包小吃休闲食品整箱送女友网红猪饲料礼物网红小七夕礼物',
                            price: '59.90'
                        },
                        {
                            id: 6,
                            imgUrl: '/images/dalibao3.jpeg',
                            name: '百草味零食大礼包肉食类充饥夜宵一整箱巨型组合装儿童礼物送女友，12款纯肉食大包装 袋袋过瘾',
                            price: '89.00'
                        },
                        {
                            id: 7,
                            imgUrl: '/images/xiongmaogaodian.png',
                            name: '好利来熊猫竹竹点心零食糕点点心早餐小吃礼盒',
                            price: '28.00'
                        },
                        {
                            id: 8,
                            imgUrl: '/images/fengzhua.jpeg',
                            name: '王小卤虎皮凤爪爆款零食小吃 休闲食品鸡爪子卤味熟食解馋小零食',
                            price: '24.95'
                        },
                        {
                            id: 9,
                            imgUrl: '/images/moyushuang.jpeg',
                            name: '卫龙魔芋爽辣条魔芋素毛肚素肉好吃办公室零食小吃休闲食品大礼包',
                            price: '16.90'
                        },
                        {
                            id: 10,
                            imgUrl: '/images/shushi.jpeg',
                            name: '谭八爷麻辣冷吃牛肉100g*4袋四川特产牛肉干卤味肉食熟食小吃零食',
                            price: '69.80'
                        },
                        {
                            id: 11,
                            imgUrl: '/images/yashe.jpeg',
                            name: '王小卤香辣酱鸭舌温州特产鸭舌头卤味熟食健康零食小吃',
                            price: '26.25'
                        },
                        {
                            id: 12,
                            imgUrl: '/images/binggan2.jpeg',
                            name: '好利来葡萄奶酥2枚入夹心饼干甜品糕点食品休闲零食点心早餐',
                            price: '16.00'
                        },
                        {
                            id: 13,
                            imgUrl: '/images/mianbao2.jpeg',
                            name: '甜苦瓜 咸蛋黄牛奶手撕面包奶香夹心吐司手工营养早餐零食品整箱',
                            price: '19.90'
                        },
                        {
                            id: 14,
                            imgUrl: '/images/mianbao3.jpeg',
                            name: '七年五季全麦欧包0低脂面包休闲零食品无蔗糖粗粮饱腹小吃早代餐',
                            price: '24.90'
                        }

                    ]

                }
            ]
        }
    })
});

//首页零食礼包的数据
router.get('/api/index_list/1/data/1', function(req, res, next) {
    res.send({
        data: [{
                id: 1,
                type: 'adList',
                data: [{
                    id: 0,
                    imgUrl: './images/dalibao.jpeg'
                }, ]
            },
            {
                id: 2,
                type: 'likeList',
                data: [{
                        id: 1,
                        imgUrl: '/images/recommend1.jpeg',
                        name: '爆款零食大礼包',
                        price: '69.80'
                    },
                    {
                        id: 5,
                        imgUrl: '/images/dalibao2.jpeg',
                        name: '零食大礼包小吃休闲食品整箱送女友网红猪饲料礼物网红小七夕礼物',
                        price: '59.90'
                    },
                    {
                        id: 6,
                        imgUrl: '/images/dalibao3.jpeg',
                        name: '百草味零食大礼包',
                        price: '89.00'
                    }

                ]
            }
        ]

    })
})



//查询商品数据接口
router.get('/api/goods/shopList', function(req, res, next) {
    //前端传递给后端的数据 获得他们的属性名 ordername为对象的名称 price/num
    let [searchName, ordername] = Object.keys(req.query)

    //前端传递给后端的 升降序的对象 以及是升序还是降序
    let [name, order] = Object.values(req.query)

    //使用到了数据库的查询语句
    connection.query('select * from goods_list where content like "%' + name + '%" order by ' + ordername + ' ' + order + '', function(err, results) {
        res.send({
            code: 0,
            data: results
        })
    })
})

//火爆商品以及查询商品为空时的接口
router.get('/api/goods/hotList', function(req, res, next) {
    //根据 price/num 
    let ordername = Object.keys(req.query) || 'num'
        //升序降序
    let orderBy = Object.values(req.query) || 'DESC'
        //让其显示销量最好的5件商品

    if (ordername.length > 0) {
        connection.query(`select * from goods_list order by ${ordername} ${orderBy} limit 5`, function(err, results) {
            res.send({
                data: results
            })
        })
    } else {
        connection.query('select * from goods_list order by num DESC limit 5', function(err, results) {
            res.send({
                data: results
            })
        })
    }
})

//分类的接口
router.get('/api/goods/list', function(req, res, next) {
    res.send({
        code: 0,
        data: [
            //一级（左侧导航栏）
            {
                id: 0,
                name: '推荐',
                data: [{
                    //二级（右侧标题）
                    id: 0,
                    name: '推荐',
                    list: [
                        //三级（右侧小图片以及文字）
                        {
                            id: 0,
                            name: '熟食',
                            imgUrl: '/images/roushi.jpeg'
                        },
                        {
                            id: 1,
                            name: '礼包',
                            imgUrl: '/images/零食礼包.jpeg'
                        },
                        {
                            id: 2,
                            name: '辣条',
                            imgUrl: '/images/latiao.jpeg'
                        },
                        {
                            id: 3,
                            name: '甜品',
                            imgUrl: '/images/tianping.jpeg'
                        },
                        {
                            id: 4,
                            name: '面包',
                            imgUrl: '/images/mianbao.jpeg'
                        },
                    ]
                }]
            },
            {
                id: 1,
                name: '零食礼包',
                data: [{
                    //二级（右侧标题）
                    id: 0,
                    name: '零食礼包',
                    list: [
                        //三级（右侧小图片以及文字）
                        {
                            id: 0,
                            name: '礼包',
                            imgUrl: '/images/零食礼包.jpeg'
                        },
                    ]
                }]
            },
            {
                id: 2,
                name: '干货',
                data: [{
                    //二级（右侧标题）
                    id: 0,
                    name: '干货',
                    list: [
                        //三级（右侧小图片以及文字）
                        {
                            id: 0,
                            name: '面包',
                            imgUrl: '/images/mianbao.jpeg'
                        },
                        {
                            id: 0,
                            name: '饼干',
                            imgUrl: '/images/binggan.jpeg'
                        }
                    ]
                }]
            },
            {
                id: 3,
                name: '辣条',
                data: [{
                    //二级（右侧标题）
                    id: 0,
                    name: '辣条',
                    list: [
                        //三级（右侧小图片以及文字）
                        {
                            id: 0,
                            name: '辣条',
                            imgUrl: '/images/latiao.jpeg'
                        },

                    ]
                }]
            },
            {
                id: 4,
                name: '熟食',
                data: [{
                    //二级（右侧标题）
                    id: 0,
                    name: '熟食',
                    list: [
                        //三级（右侧小图片以及文字）
                        {
                            id: 0,
                            name: '熟食',
                            imgUrl: '/images/roushi.jpeg'
                        },
                    ]
                }]
            },
            {
                id: 5,
                name: '甜品',
                data: [{
                    //二级（右侧标题）
                    id: 0,
                    name: '甜品',
                    list: [
                        //三级（右侧小图片以及文字）
                        {
                            id: 0,
                            name: '甜品',
                            imgUrl: '/images/tianping.jpeg'
                        },
                    ]
                }]
            },

        ]
    })
});

//查询商品id的接口（商品详情跳转到对应的界面）
router.get('/api/goods/id', function(req, res, next) {
    let id = req.query.id
    connection.query('select * from goods_list where id = ' + id + '', function(err, results) {
        if (err) throw err
        res.send({
                data: results[0],
            })
            // console.log(results[0])
    })

})

//登录（查询用户用户名以及密码接口，不存在则提示用户不存在）
router.post('/api/login', function(req, res, next) {
    //后端接受前端传递的值
    let params = {
        userTel: req.body.userTel,
        userPwd: req.body.userPwd
    }

    //用户信息
    let payload = { tel: params.userTel }
        //口令
    let secret = 'songjie'
        //生成token
    let token = jwt.sign(payload, secret, {
        //token过期时间
        expiresIn: 600
    })
    let tokenObj = jwt.decode(token)
    console.log(tokenObj)
        //查询用户手机号
    connection.query(user.queryUserTel(params), function(err, results) {
        //手机号存在
        if (results.length > 0) {
            //查询密码
            //当前登录用户的id
            let id = results[0].id
            connection.query(user.queryUserPwd(params), function(err, result) {
                if (result.length > 0) {
                    //每次登录都更新token
                    connection.query(`update user set token ="${token}" where id = ${id}`, function(e, r) {
                        //密码正确
                        res.send({
                            code: 200,
                            data: {
                                success: true,
                                msg: '登陆成功',
                                data: results[0]
                            }
                        })
                    })

                } else {
                    //密码错误
                    res.send({
                        code: 302,
                        data: {
                            success: false,
                            msg: '密码不正确'
                        }
                    })
                }
            })
        } else {
            // 手机号不存在
            res.send({
                code: 301,
                data: {
                    success: false,
                    msg: '手机号不存在'
                }
            })
        }
    })
})

//获取短信验证码接口
router.post('/api/code', function(req, res, next) {
    let tel = req.body.phone
        // 短信应用SDK AppID
    var appid = 1400187558; // SDK AppID是1400开头

    // 短信应用SDK AppKey
    var appkey = "dc9dc3391896235ddc2325685047edc7";

    // 需要发送短信的手机号码
    var phoneNumbers = [tel];

    // 短信模板ID，需要在短信应用中申请
    var templateId = 285590; // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请

    // 签名
    var smsSign = "三人行慕课"; // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`

    // 实例化QcloudSms
    var qcloudsms = QcloudSms(appid, appkey);

    // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
    function callback(err, ress, resData) {
        if (err) {
            console.log("err: ", err);
        } else {
            res.send({
                code: 200,
                data: {
                    success: true,
                    data: ress.req.body.params[0],
                }
            })
            console.log("request data: ", ress.req);
            console.log("response data: ", resData);
        }
    }

    var ssender = qcloudsms.SmsSingleSender();
    //往手机发送的短信
    var params = [Math.floor(Math.random() * 999999) + 1];
    ssender.sendWithParam(86, phoneNumbers[0], templateId,
        params, smsSign, "", "", callback); // 签名参数不能为空串
})

//登录（不存在则增加用户）
router.post('/api/adduser', function(req, res, next) {
    let params = { userTel: req.body.phone }

    //用户信息
    let payload = { tel: params.userTel }
        //口令
    let secret = 'songjie'
        //生成token
    let token = jwt.sign(payload, secret, {
        //token过期时间
        expiresIn: 600
    })

    //查询用户是否存在
    connection.query(user.queryUserTel(params), function(error, results) {
        //根据用户id进行操作
        let id = results[0].id
            //如果查询手机号存在
        if (results.length > 0) {
            connection.query(`update user set token =${token} where id =${id}`, function(e, r) {
                res.send({
                    code: 200,
                    data: {
                        success: true,
                        msg: '登陆成功',
                        data: results[0]
                    }
                })
            })

        } else {
            //不存在 新增一条数据
            connection.query(user.insertData(params), function(error, results) {
                connection.query(user.queryUserTel(params), function(e, r) {
                    res.send({
                        code: 200,
                        data: {
                            success: true,
                            msg: '登陆成功',
                            data: r[0]
                        }
                    })
                })
            })
        }
    })
})

//注册用户
router.post('/api/register', function(req, res, next) {
    let params = { userTel: req.body.phone, userPwd: req.body.userPwd }
        //查询注册的用户是否存在
    connection.query(user.queryUserTel(params), function(error, results) {
        //如果存在
        if (results.length > 0) {
            res.send({
                code: 200,
                data: {
                    msg: '用户已存在',
                    success: false,
                }
            })
        } else {
            //不存在则加入数据库
            connection.query(user.register(params), function(error, results) {
                connection.query(user.queryUserTel(params), function(e, r) {
                    res.send({
                        code: 200,
                        data: {
                            success: true,
                            msg: '注册成功',
                            data: r[0]
                        }
                    })
                })
            })
        }
    })
})

//找回密码(验证用户是否存在)
router.post('/api/selectUser', function(req, res, next) {
    let params = { userTel: req.body.phone }
    connection.query(user.queryUserTel(params), function(error, results) {
        //如果存在
        if (results.length > 0) {
            //下一步
            res.send({
                code: 200,
                data: {
                    success: true,
                    msg: ''
                }
            })
        } else {
            // 不存在
            res.send({
                code: 0,
                data: {
                    success: false,
                    msg: '此用户不存在'
                }
            })
        }
    })

})

//修改密码
router.post('/api/recovery', function(req, res, next) {
    let params = {
            userTel: req.body.phone,
            userPwd: req.body.userPwd
        }
        //首先查询手机号是否存在 得到他的id值 根据ID来修改密码
    connection.query(user.queryUserTel(params), function(err, results) {
        let id = results[0].id
            // let pwd = results[0].pwd
            // connection.query(`update user set pwd=replace(pwd,'${pwd}',' ${params.userPwd}') where id = '${id}' `, function(e, r) {
            //     res.send({
            //         code: 200,
            //         data: {
            //             success: true,
            //             msg: '修改成功',
            //             data: r
            //         }
            //     })
            // })
        connection.query('UPDATE user SET pwd ="' + params.userPwd + '" WHERE (id =' + id + ')', function(e, r) {
            res.send({
                code: 200,
                data: {
                    success: true,
                    msg: '修改成功',
                    data: r
                }
            })
        })
    })
})

//加入购物车（添加至购物车）
router.post('/api/addCart', function(req, res, next) {
    //后端接受前端传递的参数（用户id）
    let goodsId = req.body.goodsId

    //得到用户token判断是哪个用户进行操作
    let token = req.headers.token

    //得到的tel的结果是一个对象，里面是用户信息，过期时间
    let tokenObj = jwt.decode(token)


    //判断token是否过期(如果执行 证明token过期)
    if (getTimeToken(tokenObj.exp)) {
        res.send({
            data: {
                success: true,
                code: 1000,
                msg: '登录状态过期，请重新登录'
            }
        })
        return
    }



    //根据手机号查询token中的用户信息（手机号）
    connection.query('select * from user where (tel =' + tokenObj.tel + ') ', function(error, results) {
        //进行加入购物车操作的用户ID
        let uId = results[0].id
            //查询商品(根据商品id查询)
        connection.query(`select * from goods_list where id =${goodsId}`, function(err, result) {
            let goodsName = result[0].name
            let goodsPrice = result[0].price
            let goodsImgUrl = result[0].imgUrl
                //查询当前用户在之前是否添加过本商品
            connection.query(`select * from goods_cart where uId= ${uId} and goods_id = ${goodsId}`, function(e, r) {
                //如果查询结果大于0证明购物车中有该商品

                if (r.length > 0) {
                    let num = r[0].goods_num

                    connection.query(`update goods_cart set goods_num ="${parseInt(num)+1}" where id= "${r[0].id}"`, function(ee, rr) {
                        res.send({
                            data: {
                                success: true,
                                msg: '已添加',
                                code: 200,
                            }
                        })
                    })

                } else {
                    //新增数据（加入购物车的数据）
                    connection.query(`insert into goods_cart (uId,goods_id,goods_name,goods_price,goods_num,goods_imgUrl) values ("${uId}","${goodsId}","${goodsName}","${goodsPrice}","1","${goodsImgUrl}")`, function(e, r) {
                        res.send({
                            data: {
                                code: 200,
                                success: true,
                                msg: '已添加'
                            }
                        })
                    })
                }
            })
        })


    })
})

//查询购物车数据
router.post('/api/selectCart', function(req, res, next) {
    //token
    let token = req.headers.token
        //token解码 得到用户信息和token有效时间
    let tokenObj = jwt.decode(token)
        //判断token是否过期(如果执行 证明token过期)
    if (getTimeToken(tokenObj.exp)) {
        res.send({
            data: {
                success: true,
                code: 1000,
                msg: '登录状态过期，请重新登录'
            }
        })
        return
    }
    //查询用户
    connection.query('select * from user where (tel =' + tokenObj.tel + ') ', function(error, results) {
        let uId = results[0].id
        console.log(uId)
            //查询购物车
        connection.query('select * from goods_cart where (uId = ' + uId + ')', function(err, result) {
            res.send({
                data: {
                    code: 200,
                    msg: '查询成功',
                    success: true,
                    data: result
                }
            })
        })
    })
    return
})

//删除购物车数据
router.post('/api/deleteCart', function(req, res, next) {
    //前端传递的要进行操作的购物车id数组
    let cartId = req.body.cartId
    for (let i = 0; i < cartId.length; i++) {
        connection.query(`delete from goods_cart where id = ${cartId[i]}`, function(error, results) {

        })
    }
    res.send({
        data: {
            msg: '删除成功',
            code: 200,
            success: true
        }
    })
    return
})

//更新购物车商品数量
router.post('/api/updateNum', function(req, res, next) {
    let params = {
        num: req.body.num,
        id: req.body.id
    }
    connection.query(`update goods_cart set goods_num ="${params.num}" where id= "${params.id}"`, function(error, results) {
        res.send({
            data: {
                success: true,
                code: 200,
                data: results[0]
            }
        })
    })
    return
})

//新增地址数据
router.post('/api/addAddress', function(req, res, next) {
    //前端传递的存储地址数据
    //token
    let token = req.headers.token

    //token解码 得到用户信息和token有效时间
    let tokenObj = jwt.decode(token)

    //判断token是否过期(如果执行 证明token过期)
    if (getTimeToken(tokenObj.exp)) {
        res.send({
            data: {
                success: true,
                code: 1000,
                msg: '登录状态过期，请重新登录'
            }
        })
        return
    }
    //用户地址信息
    let content = req.body.content
    let [name, tel, province, city, county, addressDetail, isDefault, areaCode] = [
        content.name, //用户名
        content.tel, //用户手机号
        content.province, //省
        content.city, //市
        content.county, //区
        content.addressDetail, //详细地址
        content.isDefault, //是否设置为默认地址
        content.areaCode, //地区编码
    ]

    //获取要修改哪个用户的地址
    connection.query(`select * from user where tel = ${tokenObj.tel}`, function(error, results) {
        //uId表示当前用户id
        let uId = results[0].id
            //如果默认地址未勾选
        if (isDefault != 1) {
            // 查询地址栏里有无地址 ，如果地址为空，则设置的第一个地址为默认地址
            connection.query(`select * from address where uId =${uId} and isDefault =1`, function(e, r) {
                if (r.length > 0) {
                    //如果存在默认地址
                    connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values ("${uId}","${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function(err, result) {
                        res.send({
                            data: {
                                success: true,
                                code: 200,
                                msg: '添加地址成功',
                                data: result[0]
                            }
                        })
                    })
                } else {
                    //不存在默认地址 直接令第一个加入的数据为默认地址
                    connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values ("${uId}","${name}","${tel}","${province}","${city}","${county}","${addressDetail}","1","${areaCode}")`, function(err, result) {
                        res.send({
                            data: {
                                success: true,
                                code: 200,
                                msg: '添加地址成功，默认地址设置为当前地址',
                                data: result[0]
                            }
                        })
                    })
                }
            })
        } else {
            //勾选为默认地址(查询进行当前操作的用户 以及用户是否有默认地址)
            connection.query(`select * from address where uId = ${uId} and isDefault = ${isDefault}`, function(err, result) {
                //如果有勾选过的默认地址
                if (result.length) {
                    let addressId = result[0].id
                        //取消之前存在的默认地址
                    connection.query(`update address set isDefault = 0 where id = ${addressId}`, function(e, r) {
                        //存储地址
                        connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values ("${uId}","${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function(ee, rr) {
                            console.log(rr)
                            res.send({
                                data: {
                                    success: true,
                                    code: 200,
                                    msg: '添加地址成功',
                                    data: rr[0]
                                }
                            })
                        })
                    })
                } else {
                    //没有勾选过的默认地址直接存储
                    //存储地址
                    connection.query(`insert into address (uId,name,tel,province,city,county,addressDetail,isDefault,areaCode) values ("${uId}","${name}","${tel}","${province}","${city}","${county}","${addressDetail}","${isDefault}","${areaCode}")`, function(ee, rr) {
                        res.send({
                            data: {
                                success: true,
                                code: 200,
                                msg: '添加地址成功',
                                data: rr[0]
                            }
                        })
                    })
                }




            })
        }


    })

})

//查询收货地址
router.get('/api/selectAddress', function(req, res, next) {
    //前端传递的存储地址数据
    //token
    let token = req.headers.token

    //token解码 得到用户信息和token有效时间
    let tokenObj = jwt.decode(token)
        //判断token是否过期(如果执行 证明token过期)
    if (getTimeToken(tokenObj.exp)) {
        res.send({
            data: {
                success: true,
                code: 1000,
                msg: '登录状态过期，请重新登录'
            }
        })
        return
    }

    connection.query('select * from user where tel = ' + tokenObj.tel + '', function(error, results) {
        //得到用户的id（使数据库知道是哪个用户进行操作，查询哪个用户的数据）
        let uId = results[0].id
        connection.query(`select * from address where uId = ${uId}`, function(error, result) {
            res.send({
                data: {
                    success: true,
                    data: result,
                    msg: '查询成功'
                }
            })
        })
    })

})

//更改收货地址
router.post('/api/updateAddress', function(req, res, next) {
    //获取要修改哪个用户的地址
    let token = req.headers.token
    let tokenObj = jwt.decode(token)

    //用户地址信息
    let AddressInfo = req.body.AddressInfo
    let [id, name, tel, province, city, county, addressDetail, isDefault, areaCode] = [
        AddressInfo.id, //记录地址id
        AddressInfo.name, //用户名
        AddressInfo.tel, //用户手机号
        AddressInfo.province, //省
        AddressInfo.city, //市
        AddressInfo.county, //区
        AddressInfo.addressDetail, //详细地址
        AddressInfo.isDefault, //是否设置为默认地址
        AddressInfo.areaCode, //地区编码
    ]

    connection.query(`select * from user where tel = ${tokenObj.tel}`, function(errors, results) {
        //获取当前要修改地址的用户id
        let uId = results[0].id
            //查询之前有没有默认地址
        connection.query(`select * from address where uId = ${uId} and isDefault =${isDefault}`, function(error, result) {
            console.log(result)
            if (result.length > 0) {
                let addressId = result[0].id
                    //之前设置过默认地址(把其他地址设置为非默认地址)
                connection.query(`update address set isDefault = 0 where id = ${addressId}`, function(e, r) {
                    //修改地址
                    let updateSql = `update address set uId =? , name =? , tel =? , province=? , city =? , county =? , addressDetail=? , isDefault =? , areaCode =? where id ="${id}"`
                    connection.query(updateSql, [uId, name, tel, province, city, county, addressDetail, isDefault, areaCode], function(ee, rr) {
                        res.send({
                            data: {
                                success: true,
                                msg: '修改成功',
                                data: rr
                            }
                        })
                    })
                })
            } else {
                //修改地址
                let updateSql = `update address set uId =? , name =? , tel =? , province=? , city =? , county =? , addressDetail=? , isDefault =? , areaCode =? where id ="${id}"`
                connection.query(updateSql, [uId, name, tel, province, city, county, addressDetail, isDefault, areaCode], function(ee, rr) {
                    res.send({
                        data: {
                            success: true,
                            msg: '修改成功',
                            data: rr
                        }
                    })
                })
            }
        })

    })
})

//删除地址
router.post('/api/deleteAddress', function(req, res, next) {
    let id = req.body.id
    connection.query(`delete from address where id =${id}`, function(err, result) {
        res.send({
            data: {
                success: true,
                msg: '删除成功',
            }
        })
    })
})

//生成订单
router.post('/api/addOrder', function(req, res, next) {
    //获取用户token
    let token = req.headers.token

    //token解码 得到用户信息和token有效时间
    let tokenObj = jwt.decode(token)

    //判断token是否过期(如果执行 证明token过期)
    if (getTimeToken(tokenObj.exp)) {
        res.send({
            data: {
                success: true,
                code: 1000,
                msg: '登录状态过期，请重新登录'
            }
        })
        return
    }

    //前端传递的 在购物车中选中的商品 选中商品总价
    let goodsArr = req.body.goodsChecked
    let total = req.body.total

    //生成订单号order_id ,规则：时间戳+6位随机数
    function setTimeDataFmt(s) {
        //补0函数
        return s < 10 ? '0' + s : s
    }

    function randomNumber() {
        const now = new Date()
        let month = setTimeDataFmt(now.getMonth() + 1)
        let day = setTimeDataFmt(now.getDate())
        let hour = setTimeDataFmt(now.getHours())
        let minute = setTimeDataFmt(now.getMinutes())
        let seconds = setTimeDataFmt(now.getSeconds())

        let orderCode = now.getFullYear().toString() + month.toString() + day.toString() + hour.toString() + minute.toString() + seconds.toString() + Math.round(Math.random() * 1000000).toString()

        return orderCode
    }
    /* 支付状态
    未支付：1
    待支付：2
    支付成功：3
    支付失败：4 ||0
    */

    //商品列表名称
    let goodsName = []
        //订单总金额
    let goodsPrice = total.price
        //订单商品总数量
    let goodsNum = total.num
        //订单号
    let orderId = randomNumber()

    goodsArr.forEach(v => {
        goodsName.push(v.goods_name)
    })

    //查询当前进行操作的用户
    connection.query(`select * from user where tel =${tokenObj.tel}`, function(error, results) {
        let uId = results[0].id
            //生成订单号以及对应的信息
        connection.query(`insert into store_order (order_id,uId,goods_name,goods_price,goods_num,order_status) values ("${orderId}","${uId}","${goodsName}","${goodsPrice}","${goodsNum}","1")`, function(err, result) {
            //查询订单号以及操作状态是否为1
            connection.query(`select * from store_order where uId =${uId} and  order_id  = "${orderId}"`, function(e, r) {
                res.send({
                    data: {
                        success: true,
                        code: 200,
                        data: r
                    }
                })
            })
        })
    })
})

//查询订单
router.post('/api/selectOrder', function(req, res, next) {
    //获得前端给后端传递的订单号
    let orderId = req.body.orderId
        //直接查询订单号即可（因为对应了哪个用户操作）
    connection.query(`select * from store_order where order_id =${orderId}`, function(error, results) {
        res.send({
            data: {
                code: 200,
                success: true,
                data: results
            }
        })
    })
})

//修改订单状态
router.post('/api/submitOrder', function(req, res, next) {
    //获取用户token
    let token = req.headers.token

    //token解码 得到用户信息和token有效时间
    let tokenObj = jwt.decode(token)

    //判断token是否过期(如果执行 证明token过期)
    if (getTimeToken(tokenObj.exp)) {
        res.send({
            data: {
                success: true,
                code: 1000,
                msg: '登录状态过期，请重新登录'
            }
        })
        return
    }
    //订单号
    let orderId = req.body.orderId

    //购物车选中的数据
    let shopArr = req.body.shopArr

    //查询是哪个用户在操作
    connection.query(`select * from user where tel = ${tokenObj.tel}`, function(errors, results) {
        let uId = results[0].id
            //取得对应订单的id
        connection.query(`select * from store_order where uId=${uId} and order_id =${orderId}`, function(error, result) {
            let oId = result[0].id
                //修改订单状态 1==>2 未支付改成待支付
            connection.query(`update store_order set order_status ='2' where id =${oId} `, function(e, r) {
                //删除选中的购物车数据
                shopArr.forEach(v => {
                    connection.query(`delete from goods_cart where id =${v.id} `, function(ee, rr) {

                    })
                })
                res.send({
                    data: {
                        success: true,
                        msg: '订单状态为2.待支付,商品已删除'
                    }
                })
            })

        })
    })
    return
})

//发起支付(支付宝)
router.post('/api/payment', function(req, res, next) {
    //订单号
    let orderId = req.body.orderId
        //商品总价格
    let price = req.body.price
        //商品名称
    let goodsName = req.body.name
        //开始对接支付宝api
        //支付宝配置
    const formData = new AlipayFormData()
        //调用setMethod 并传入get，会返回可以跳转到支付页面的url
    formData.setMethod('get')
        //支付时信息
    formData.addField('bizContent', {
            outTradeNo: orderId, // 商户订单号,64个字符以内、可包含字母、数字、下划线,且不能重复
            productCode: 'FAST_INSTANT_TRADE_PAY', // 销售产品码，与支付宝签约的产品码名称,仅支持FAST_INSTANT_TRADE_PAY
            totalAmount: price, // 订单总金额，单位为元，精确到小数点后两位
            subject: goodsName, // 商品名称
        })
        //支付成功或者支付失败跳转的链接
    formData.addField('returnUrl', 'http://localhost:8081/payment');
    //返回promise
    const result = alipaySdk.exec( // result 为可以跳转到支付链接的 url
        'alipay.trade.page.pay', // 统一收单下单并支付页面接口
        {}, // api 请求的参数（包含“公共请求参数”和“业务参数”）
        { formData: formData },
    );
    //对接支付宝成功，支付宝方返回的数据（url）
    result.then(resp => {
        res.send({
            data: {
                code: 200,
                success: true,
                msg: '支付中',
                paymentUrl: resp
            }
        })
    })


})

//支付状态（成功、失败）
router.post('/api/successPayment', function(req, res, next) {
    let token = req.headers.token
    let tokenObj = jwt.decode(token)
        //订单号
    let out_trade_no = req.body.out_trade_no
    let trade_no = req.body.trade_no
        //支付宝配置
    const formData = new AlipayFormData()
        //调用setMethod 并传入get，会返回可以跳转到支付页面的url
    formData.setMethod('get')
        //支付时信息
    formData.addField('bizContent', {
            out_trade_no,
            trade_no,
        })
        //返回promise
    const result = alipaySdk.exec( // result 为可以跳转到支付链接的 url
            'alipay.trade.query', // 和支付不同的是 这里的参数是query
            {}, // api 请求的参数（包含“公共请求参数”和“业务参数”）
            { formData: formData },
        )
        //后端请求支付宝
    result.then(resData => {
        axios({
            method: 'GET',
            url: resData
        }).then(data => {
            let responseCode = data.data.alipay_trade_query_response.code
            if (responseCode.code == '10000') {
                //进入到支付状态
                switch (responseCode.trade_status) {
                    case 'WAIT_BUYER_PAY ':
                        res.send({
                            data: {
                                code: 0,
                                data: {
                                    success: false,
                                    msg: '支付宝有交易记录，没付款'
                                }
                            }
                        })
                        break;
                    case 'TRADE_CLOSED':
                        res.send({
                            data: {
                                code: 1,
                                data: {
                                    success: false,
                                    msg: '交易关闭'
                                }
                            }
                        })
                        break;
                    case 'TRADE_SUCCESS': //在交易完成后把改订单状态
                        // 查询是哪个用户在操作
                        connection.query(`select * from user where tel = ${tokenObj.tel}`, function(errors, results) {
                            let uId = results[0].id
                                //查询订单
                            connection.query(`select * from store_order where uId= ${uId} and order_id =${out_trade_no}`, function(error, result) {
                                let id = result[0].id //订单id
                                    //修改订单状态
                                connection.query(`update store_order set order_status ="3" where id =${id}`, function(e, r) {
                                    res.send({
                                        data: {
                                            code: 2,
                                            data: {
                                                success: true,
                                                msg: '交易完成'
                                            }
                                        }
                                    })
                                })
                            })
                        })
                        break;

                }
            } else if (responseCode.code == '40004') {
                res.send({
                    data: {
                        code: 4,
                        data: {
                            msg: '交易不存在'
                        }
                    }
                })
            }
        }).catch(err => {
            res.send({
                data: {
                    code: 500,
                    msg: '交易失败',
                    err
                }
            })
        })
    })
})

module.exports = router